#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-10 下午3:07
from flask import Flask
from flask.json import jsonify


class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        self.message = message

        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        rv['status_code'] = self.status_code
        return rv


app = Flask(__name__)


@app.route("/", methods=['GET'])
def index():
    raise InvalidUsage("error1", status_code=401)


@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    return jsonify(error.to_dict())


if __name__ == '__main__':
    app.run(debug=True)